package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CallApi;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.ReceiveCall;
import com.tanhua.model.mongo.SendCall;
import com.tanhua.model.vo.CallVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Service
public class CallService {

    @DubboReference
    private CallApi callApi;
    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private FastFileStorageClient client;
    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private FriendApi friendApi;

    public void sendCall(MultipartFile soundFile) throws IOException {
        //拿到用户id
        Long userId = UserHolder.getUserId();
        //拿到时间
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        //从idea中拿到值
        Object redis = redisTemplate.opsForHash().get(Constants.SEND_CALL_KEY, userId.toString());
        Integer count = 0;
        //判断redis中是否有数据
        if (redis != null) {
            count = Integer.valueOf(redis.toString()) ;
        }
        //判断是否大于10
        if (count >= 10) {
            //大于等于10
            throw new BusinessException(ErrorResult.sendError());
        }
        //不大于10
        //拿到soundUrl
        //拿到文件的名称
        String filename = soundFile.getOriginalFilename();  // abc.mp4
        //截取后缀名，拿到soundUrl
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), filename, null);
        String soundUrl = webServer.getWebServerUrl() + storePath.getFullPath();

        SendCall sendCall = new SendCall();
        //userId
        sendCall.setUserId(userId);
        //createDate
        sendCall.setCreatedDate(date);
        //soundUrl
        sendCall.setSoundUrl(soundUrl);
        //保存进数据库
        callApi.saveSendCall(sendCall);
        //将数据存到redis中
        redisTemplate.opsForHash().put(Constants.SEND_CALL_KEY, userId.toString(), String.valueOf(count + 1));
    }

    public CallVo receiveCall() {
        //拿到用户id
        Long userId = UserHolder.getUserId();
        //拿到时间
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        Object redis = redisTemplate.opsForHash().get(Constants.RECEIVE_CALL_KEY, userId.toString());
        int count = 0;
        //判断redis中是否有数据
        if (redis != null) {
            count = Integer.valueOf(redis.toString()) ;
        }
        //判断是否大于10
        if (count >= 10) {
            //大于等于10
            throw new BusinessException(ErrorResult.receiveError());
        }
        //拿到对应好友的id
        List<Friend> friends = friendApi.getByUserId(userId);
        List<Long> friendId = CollUtil.getFieldValues(friends, "friendId", Long.class);
        friendId.add(userId);
        //拿到对应的数据
        SendCall sendCall = callApi.getIsNotZero(friendId);
        if (sendCall == null) {
            throw new BusinessException(ErrorResult.receiveErrorTwo());
        }
        //拿到语音对应的用户id
        Long id = sendCall.getUserId();
        //拿到soundUrl
        String soundUrl = sendCall.getSoundUrl();
        //拿到用户的对象
        UserInfo userInfo = userInfoApi.findById(id);
        //构建保存的对象
        ReceiveCall receiveCall = new ReceiveCall();
        receiveCall.setSendCallId(sendCall.getId());
        receiveCall.setUserId(userId);
        receiveCall.setCreatedDate(date);
        //将数据存到数据库
        callApi.saveReceiveCall(receiveCall);
        //构造返回的对象
        CallVo callVo = new CallVo();
        //赋值对应的属性
        BeanUtils.copyProperties(userInfo, callVo);
        //soundUrl
        callVo.setSoundUrl(soundUrl);
        //给出redis中的数据+1
        redisTemplate.opsForHash().put(Constants.RECEIVE_CALL_KEY, userId.toString(), String.valueOf(count + 1));
        //remainingTimes
        callVo.setRemainingTimes(10 - count);
        return callVo;
    }
}
